package com.season.summer.bspgenerator.service.impl;


import com.season.summer.bspgenerator.dao.GeneratorDao;
import com.season.summer.bspgenerator.entity.PackageInfo;
import com.season.summer.bspgenerator.entity.TableEntity;
import com.season.summer.bspgenerator.service.GeneratorService;
import com.season.summer.bspgenerator.utils.GeneratorUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器
 */
@Service
public class GeneratorServiceImpl implements GeneratorService {

    @Autowired
    private GeneratorDao generatorDao;

    @Override
    public List<TableEntity> list(String tableName) {
        return generatorDao.list(tableName);
    }

    @Override
    public void generatorCode(PackageInfo packageInfo) {
        String tableName = packageInfo.getTableName();
        //查询列信息
        List<Map<String, String>> columns = queryColumns(tableName);
        GeneratorUtil.generatorCode(packageInfo, columns, null);
    }

    @Override
    public PackageInfo getPackageInfo(String tableName) {
        PackageInfo info = new PackageInfo();
        String className;
        if (tableName.startsWith(GeneratorUtil.tablePrefix)) {
            String substring = tableName.substring(GeneratorUtil.tablePrefix.length());
            className = GeneratorUtil.columnToJava(substring);
        } else {
            className = GeneratorUtil.columnToJava(tableName);
        }
        info.setTableName(tableName);
        info.setClassName(className);
        info.setPackagePath(GeneratorUtil.packagePath);
        info.setProjectPath(GeneratorUtil.projectPath);
        info.setModuleName(className.toLowerCase());
        return info;
    }

    @Override
    public byte[] generatorCodeZip(PackageInfo packageInfo) {
        String tableName = packageInfo.getTableName();
        //查询列信息
        List<Map<String, String>> columns = queryColumns(tableName);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);

        //生成代码
        GeneratorUtil.generatorCode(packageInfo, columns, zip);
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    private List<Map<String, String>> queryColumns(String tableName) {
        return generatorDao.queryColumns(tableName);
    }

}
